function varargout = prfft(varargin)
% PRFFT M-file for prfft.fig
%      PRFFT, by itself, creates a new PRFFT or raises the existing
%      singleton*.
%
%      H = PRFFT returns the handle to a new PRFFT or the handle to
%      the existing singleton*.
%
%      PRFFT('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PRFFT.M with the given input arguments.
%
%      PRFFT('Property','Value',...) creates a new PRFFT or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before prfft_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to prfft_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help prfft

% Last Modified by GUIDE v2.5 31-Jan-2012 14:18:09

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @prfft_OpeningFcn, ...
                   'gui_OutputFcn',  @prfft_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before prfft is made visible.
function prfft_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to prfft (see VARARGIN)

% Choose default command line output for prfft
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes prfft wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = prfft_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;
function psnr1(hObject, eventdata, handles)
imagen=handles.BW1;
marcada=handles.BW2;
if (size(imagen)~=size(marcada)) 
   error('Las imagenes deben tener el mismo tamaño') 
end 
if (~isrgb(imagen) & ~isrgb(marcada)) 
   [m n] = size(imagen); 
   A=double(imagen); 
   B=double(marcada); 
   sumaDif=0; 
   maxI=m*n*max(max(A.^2)); 
   
   for u=1:m 
      for v=1:n 
         sumaDif = sumaDif + (B(u,v)-A(u,v))^2; 
      end 
   end 
   
   if (sumaDif==0)  
      sumaDif=1; 
   end 
   S=(maxI/sumaDif); 
   S=10*log10(S);	 
else  
   error('Las imagenes no pueden ser en color') 
end 
set(handles.txtpsnr,'String',num2str(abs(S)));
guidata(hObject, handles);

function psnr(hObject, eventdata, handles)
imagen=double(handles.BW1);
marcada=double(handles.BW2);
d = mean(mean((marcada(:)-imagen(:)).^2 ) );
m1 = max( abs(marcada(:)));
m2 = max( abs(imagen(:)));
m = max(m1,m2);
p = 10*log10( m^2/d );
set(handles.txtpsnr,'String',num2str(p));
guidata(hObject, handles);

% --- Executes on button press in cmdmarcar.
function cmdmarcar_Callback(hObject, eventdata, handles)
    key = str2double(get(handles.txtkey,'String'));
   alfa =str2double(get(handles.txtalfa,'String'));
   I = double(handles.BW1);
   
   
   imp = double(I)/255.0;
   [F,C] = size(imp);
   radio = floor(sqrt((F/2)^2+(C/2)^2));
   pad1 = radio-(F/2);
   pad2 = radio-(C/2);
   im = double(zeros(F+(pad1*2),C+(pad2*2)));     % crea la matriz con el padding necesario.
   im((1+pad1):(F+pad1),(1+pad2):(C+pad2))=imp;   % inserta la imagen en la matriz.
   
   axes(handles.marcada); cla;
   imshow(im,[]);
      
  
   [M,N]=size(im);
   
   watermark=double(zeros(M,N));
   
   %******* % 1) Watermark Formation  ***************************************
   
   Lc=3;     %tamaño del mensaje
   Np=6;     %Tamaño de la secuencia bipolar
   PN=zeros(1,Np);

   NT=(M/2)*(N/2)-(Lc*Np);   %longitud del tracking sequence
   RandStream.setDefaultStream(RandStream('mt19937ar','seed',key));
   T=-1+ (1-(-1)).*rand(1,NT);    %Tracking sequence
   j=1;
   while j<=Np     % Genera PN-sequence.
       n=rand(1);
       if(n<=0.5)
           PN(j)=-1;
           PN(j+1)=1;
       else
           PN(j)=1;     % 1 -1 1 -1 -1  1
           PN(j+1)=-1;
       end
       j=j+2;
   end
   
   Mci=[1 0 1 ]; % Mensaje de tama;o Lc
   
   for j=1:Lc
           if(Mci(j)==0)
              T=[T (-1*PN)];
           else
              T=[T PN];
           end
   end
   
   W1=reshape(T,M/2,N/2);
   watermark=upsampled(W1);
   
   
  [x,y] = meshgrid(1:M,1:N);
   
  %SizeX = size(im, 1);
  %SizeY = size(im, 2);
    
  % I1 = I.*((-1).^(x+y));     % mueve las esquinas al centro
  % F1 = fft2(I1);
  % Convolve the magnitude of the FFT with a high pass filter)
  %IA = hipass_filter(size(I, 1),size(I,2)).*abs(I); 
  %L1 = Logpolar(I, SizeX, SizeY, SizeX, SizeY, 'nearest', size(IA) / 2, 'valid');
  L1=polar(im);
  % L5= polcar(L1);
  % Convert log polar magnitude spectrum to FFT
  %L2 = Logpolar(L1, SizeX, SizeY, SizeX, SizeY, 'nearest', size(IA) / 2, 'valid');
    
  Imarcada =L1;% (imR); %fft2(L1);%+(marca*alfa);
 
  %Imarcada=  ifft(mag);
   
  %phase = atan2(imag(L1),real(L1));
  %I2 = (mag.*exp(1j*phase));
 
  %I2=real(ifft2(I2));
  %Imarcada = (I2.*((-1).^(x+y)));
  
  %****
 
  I1=zeros(M,N);

  axes(handles.marcada); cla;
  imshow(Imarcada,[]);
   
  
  
  I1 = Imarcada.*((-1).^(x+y));     % mueve las esquinas al centro
  F1 = fft2(I1);
  
  mag = (sqrt(real(F1).^2 + imag(F1).^2))+(watermark*alfa);
  phase = atan2(imag(F1),real(F1));
  I2 = (mag.*exp(1j*phase));
  
  I2=real(ifft2(I2));
  I3 = (I2.*((-1).^(x+y)));
  Imarcada=cartesianas(I3);
  
  Min = min(Imarcada(:));
  Max = max(Imarcada(:));
  Imarcada = uint8(((Imarcada - Min) / (Max - Min))*255);
 
  Imagen=Imarcada(pad1+1:M-pad1,pad2+1:N-pad2);
  
  
  
  %sacar las frecuencias medias de la imagen y meterlas en la imagen
  %original
  [x,y] = meshgrid(1:F,1:C);
  img1= (double(Imagen)).*((-1).^(x+y));     % mueve las esquinas al centro
  img2 = fft2(img1);
  
  
  img3= I.*((-1).^(x+y));     % mueve las esquinas al centro
  img4 = fft2(img3);
 
  
  rmax=200;
  rmin=100;
  for s=1:F                       % Genera Marca de agua con numeros Pseudo-aleatorios
     for t=1:C
       D=((F/2-s)^2 + (C/2-t)^2)^0.5;
       if(D<=rmax && D>rmin)
         img4(s,t)=img2(s,t);
       end    
     end
  end
  
  phase1 = atan2(imag(img4),real(img4));
  I_2 = (img4.*exp(1j*phase1));
  
  I_3=real(ifft2(img4));
  res = (I_3.*((-1).^(x+y))); 
  
  
  Min = min(res(:));
  Max = max(res(:));
  resimg = uint8(((res - Min) / (Max - Min))*255);
  
  resimg()
  
  axes(handles.marcada); cla;
  imshow(resimg,[]);
  
  % imshow(F,[]);
  axes(handles.fft); cla;
  imshow(watermark);
  
  %Imagen=imread('normal.jpg');
  %axes(handles.marcada); cla;
  %imshow(Imagen,[]);
  
  handles.BW1 =uint8(I);
  handles.BW2 =uint8(resimg);
  
  handles.op=1;
  Graficar(hObject, eventdata, handles);
  psnr(hObject, eventdata, handles);
  
guidata(hObject, handles);  
   
% hObject    handle to cmdmarcar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

function Graficar(hObject, eventdata, handles)
 Imarcada=double(handles.BW2);
 Temp=Imarcada;
 op=handles.op;
 rmin=str2double(get(handles.rmin,'String'));
   rmax=str2double(get(handles.rmax,'String'));
 
 imp = double(Temp)/255.0;
 [F,C] = size(imp);
 radio = floor(sqrt((F/2)^2+(C/2)^2));
 pad1 = radio-(F/2);
 pad2 = radio-(C/2);
 im = double(zeros(F+(pad1*2),C+(pad2*2)));     % crea la matriz con el padding necesario.
 im((1+pad1):(F+pad1),(1+pad2):(C+pad2))=Temp;   % inserta la imagen en la matriz.
 
 Imarcada=polar(im);
 [F,C]=size(Imarcada);
 watermark=double(zeros(F,C));
 [x,y] = meshgrid(1:F,1:C);
 I1 = Imarcada.*((-1).^(x+y));            
 Rfft2=(fft2(I1));
 mag = (sqrt(real(Rfft2).^2 + imag(Rfft2).^2));
 
 
 vecR=[];

 for key=1:30
    W=zeros(F,C); 
   
    RandStream.setDefaultStream(RandStream('mt19937ar','seed',key));
    
    W=-1 + (1-(-1)).*rand(F/2);
  
    W2=reshape(W,F/2,C/2);
    watermark=upsampled(W2); 
       
   R=0;
   for s=1:F                           % Genera Marca de agua con numeros Pseudo-aleatorios
     for t=1:C
       D=((F/2-s)^2 + (C/2-t)^2)^0.5;
       if(D<=rmax && D>rmin)
         R=R+(watermark(s,t).*mag(s,t)); 
       end    
     end
   end
 
   vecR(key)=R;
  end
  [a b]=max(vecR);
   Mayor1=num2str(b);
  
  if(op==1)   
    set(handles.lblmax1,'String',Mayor1);
    axes(handles.grafica); %hold on; cla; 
    axis([0,100,-5000,500000]);
    plot(vecR, 'r','LineWidth', 2);
  end;
  if(op==2)  
    set(handles.lblmax2,'String',Mayor1);
    axes(handles.grafica);
    axis([0,100,-5000,500000]);
    plot(vecR, 'g','LineWidth', 2);
  end
  if(op==3)  
    set(handles.lblmax3,'String',Mayor1);
    axes(handles.grafica);
    axis([0,100,-5000,500000]);
    plot(vecR, 'y','LineWidth', 2);
  end
 handles.BW2=Temp; 
guidata(hObject, handles);

function txtpsnr_Callback(hObject, eventdata, handles)
% hObject    handle to txtpsnr (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtpsnr as text
%        str2double(get(hObject,'String')) returns contents of txtpsnr as a double


% --- Executes during object creation, after setting all properties.
function txtpsnr_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtpsnr (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
function mnuimagen_Callback(hObject, eventdata, handles)
% hObject    handle to mnuimagen (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function mnuabrir_Callback(hObject, eventdata, handles)
[filename pathname filterindex] = uigetfile('*.tif;*.bmp;*.jpg','Selecciona una imagen BMP');
if filterindex == 0
    return;
end
%set(handles.SyP,'Enable','on');
BW1 = imread([pathname filename]);
axes(handles.original); cla;
imshow(BW1);
%axes(handles.marcada); cla;
%imshow(BW1);
%axes(handles.histograma);cla;
%imhist(BW1);
handles.BW1 =uint8(BW1);
%handles.BW2 =uint8(BW1);
guidata(hObject, handles);
% hObject    handle to mnuabrir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function mnuguardad_Callback(hObject, eventdata, handles)
% hObject    handle to mnuguardad (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function mnusalir_Callback(hObject, eventdata, handles)
close;
% hObject    handle to mnusalir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)



function txtkey_Callback(hObject, eventdata, handles)
% hObject    handle to txtkey (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtkey as text
%        str2double(get(hObject,'String')) returns contents of txtkey as a double


% --- Executes during object creation, after setting all properties.
function txtkey_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtkey (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function txtalfa_Callback(hObject, eventdata, handles)
% hObject    handle to txtalfa (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtalfa as text
%        str2double(get(hObject,'String')) returns contents of txtalfa as a double


% --- Executes during object creation, after setting all properties.
function txtalfa_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtalfa (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
function mnueditar_Callback(hObject, eventdata, handles)
% hObject    handle to mnueditar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function mnurecortar_Callback(hObject, eventdata, handles)
   BW2=handles.BW2;
   axes(handles.marcada); cla;
   imshow(uint8(BW2));
   p=ginput(2);
   sp(1) = min(floor(p(1)), floor(p(2))); %xmin
   sp(2) = min(floor(p(3)), floor(p(4))); %ymin
   sp(3) = max(ceil(p(1)), ceil(p(2)));   %xmax
   sp(4) = max(ceil(p(3)), ceil(p(4)));   %ymax
   cortada=BW2;
   cortada(sp(2):sp(4),sp(1):sp(3))=0;
   axes(handles.marcada); cla;
   imshow(uint8(cortada));
   handles.BW2 =uint8(cortada);
   handles.op=2;
   Graficar(hObject, eventdata, handles);
 guidata(hObject, handles);
% hObject    handle to mnurecortar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --------------------------------------------------------------------
function mnugirar_Callback(hObject, eventdata, handles)
Mensaje = {'Grados:'};
Titulo = 'Girar';
def = {'90'};
Resp = inputdlg(Mensaje,Titulo,1,def);
if isempty(Resp)
   return;
end
[G E1] = str2num(Resp{1});
Imarcada=handles.BW2;
girada = imrotate(Imarcada,G,'bilinear','crop');
axes(handles.marcada); cla;
imshow(uint8(girada));
handles.BW2 =uint8(girada);
handles.op=3;
Graficar(hObject, eventdata, handles);
guidata(hObject, handles);



% hObject    handle to mnugirar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)



function rmin_Callback(hObject, eventdata, handles)
% hObject    handle to rmin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of rmin as text
%        str2double(get(hObject,'String')) returns contents of rmin as a double


% --- Executes during object creation, after setting all properties.
function rmin_CreateFcn(hObject, eventdata, handles)
% hObject    handle to rmin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function rmax_Callback(hObject, eventdata, handles)
% hObject    handle to rmax (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of rmax as text
%        str2double(get(hObject,'String')) returns contents of rmax as a double


% --- Executes during object creation, after setting all properties.
function rmax_CreateFcn(hObject, eventdata, handles)
% hObject    handle to rmax (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in btnsalir.
function btnsalir_Callback(hObject, eventdata, handles)
close;
% hObject    handle to btnsalir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in btnAbrir.
function btnAbrir_Callback(hObject, eventdata, handles)

[filename pathname filterindex] = uigetfile('*.tif;*.bmp;*.jpg','Selecciona una imagen BMP');
if filterindex == 0
    return;
end

BW1 = imread([pathname filename]);
axes(handles.original); cla;
imshow(BW1);
handles.BW1 =uint8(BW1);
guidata(hObject, handles);
% hObject    handle to btnAbrir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function mnusalvar_Callback(hObject, eventdata, handles)
BW2=handles.BW2;
if isempty(BW2), return, end
formatos={'*.tif','TIFF (*.tif)'; '*.png','PNG (*.PNG)'; '*.jpg','jpg (*.jpg)'; '*.bmp','BMP (*.bmp)'; };
[nombre, ruta]= uiputfile(formatos,'Guardar Imagen');
if(nombre==0), return, end
fName=fullfile(ruta,nombre);
imwrite(BW2,fName);
guidata(hObject,handles);

    


% hObject    handle to mnusalvar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
